from pkg.voice import out
from pkg.voice import in_voice
from pkg.db import db
from pkg.driver import user
import gl
import sys
import pyHook
import pythoncom
from PyQt5 import QtWidgets


def on_key_down_event(event):
    try:
        if event.Key == 'F7':
            gl.g_is_recording=True
        # print(event.MessageName)
        # print( event.Message)
        # print(event.Time)
        # print( event.Window)
        # print( event.WindowName)
        # print(event.Ascii)
        # print(event.Key)
        # print(event.KeyID)
        # print( event.ScanCode)
        # print(event.Extended)
        # print(event.Injected)
        # print( event.Alt)
        # print(event.Transition)
        return True
    except Exception as Err:
        print(Err)
        out.output('按键发生了一点异常，准备恢复')
        return True


def on_key_up_event(event):
    try:
        if event.Key == 'F7':
            gl.g_is_recording = False
        return True
    except Exception as Err:
        print(Err)
        out.output('按键发生了一点异常，准备恢复')
        return True


def set_key_hook():
    try:
        hm = pyHook.HookManager()
        hm.KeyDown = on_key_down_event
        hm.KeyUp = on_key_up_event
        hm.HookKeyboard()
        pythoncom.PumpMessages()
    except Exception as Err:
        print(Err)


def start():
    app = QtWidgets.QApplication(sys.argv)
    out.output('系统初始化完成')
    out.output('你好，欢迎使用天火智能管家系统1.0测试版本，系统已启动')
    db.build_user_msg_tab()
    users = db.get_users()
    if None == users:
        out.output('当前系统无用户，将要新建用户')
        if not user.build_user():
            out.output('系统即将退出')
            return
    users = db.get_users()
    if len(users) == 1:
        out.output('当前的用户只有')
        out.output(users[0][0]+'，')
        out.output('将登陆此用户')
        gl.g_curr_user=users[0]
    else:
        out.output('当前的用户有')
        for row in users:
            out.output(row[0] + '，')
        out.output_thread('请选择一个进行登录')
        u=user.choose_user(users)
        if u==None:
            out.output('取消登录，系统即将退出')
            return
        gl.g_curr_user=db.get_user_info(u)
        if gl.g_curr_user==None:
            out.output('登录失败，系统即将退出')
            return
    out.output(gl.g_curr_user[1])
    out.output('你好，登录成功')
    in_voice.voice_in_thread()
    set_key_hook()
    return app.exec()
